package m2acsis.algebre.anneau;

import m2acsis.algebre.ElemAnneau;
import m2acsis.algebre.ElemGroupe;
import m2acsis.algebre.helpers.ListHelper;
import m2acsis.algebre.impl.Matrice;

public class Matrice2 extends Matrice implements ElemAnneau {

	ElemAnneau[][] coefficients;
	
	public Matrice2(ElemAnneau[][] coefficients) {
		super(coefficients);
		
		this.coefficients = coefficients;
	}
	
	@Override
	public ElemGroupe neutre() {
		return new Matrice2((ElemAnneau[][]) ListHelper.getArray(getNeutreCoefficient()));
	}
	
	@Override
	public ElemGroupe oppose() {
		return new Matrice2((ElemAnneau[][]) ListHelper.getArray(getOpposeCoefficents()));
	}
	
	@Override
	public ElemGroupe somme(ElemGroupe e) {
		
		if(e instanceof Matrice2){
			
			Matrice2 me = (Matrice2)e;
			return new Matrice2((ElemAnneau[][]) ListHelper.getArray(getSommeCoefficients(me.coefficients)));
		}
		
		return null;
	}

	@Override
	public ElemAnneau inverse() {
		
		if(neutre instanceof ElemAnneau){
			
			ElemAnneau[][] inverse = new ElemAnneau[order][order]; 
			
			for(int i = 0; i < order; i++)
				for(int j = 0; j < order; j++)
				if(!coefficients[i][j].equals(coefficients[i][j].neutre()))
					inverse[i][j] = coefficients[i][j].inverse();
				else
					throw new Error("l'element " + coefficients[i][j].toString() + "n'a pas d'inverse");
			
			return new Matrice2(inverse);
		}
		
		return null;
	}

	@Override
	public ElemAnneau produit(ElemAnneau e) {
		
		if(e instanceof Matrice2){
			
			Matrice2 me = (Matrice2) e;
			
			ElemAnneau[][] coeMul = new ElemAnneau[order][order];
			
			for(int i = 0; i < order; i++)
				for(int j = 0; j < order; j++){
					coeMul[i][j] = (ElemAnneau) neutre;
				}
			
			
			for(int i = 0; i < order; i++)
				for(int j = 0; j < order; j++){
					for(int k = 0; k < order; k++)
						coeMul[i][j] = (ElemAnneau) coeMul[i][j].somme((coefficients[i][k].produit(me.coefficients[k][j])));
				}
			
			return new Matrice2(coeMul);
		}
		
		return null;
	}

	@Override
	public ElemAnneau unite() {
		
		if(neutre instanceof ElemAnneau){
			
			int pos = 0;
			ElemAnneau[][] coeUnit = new ElemAnneau[order][order];
			
			for(int i = 0; i < order; i++){
				
				for(int j = 0; j < order; j++){
					if(j == pos)
						coeUnit[i][j] = coefficients[i][j].unite();
					else
						coeUnit[i][j] = (ElemAnneau) coefficients[i][j].neutre();
				}
				pos++;
			}
			
			return new Matrice2(coeUnit);
		}
		
		return null;
	}

}
